"""
WeGame云顶之弈比赛记录爬虫：游戏场次详情

需要第三方模块：
Utils4R >= 0.0.2

@author: ChangXing
@version: 2.1
@create: 2019.12.10
@revise: 2020.06.09
"""

import json
import os

import crawlertool as tool


class SpiderTftExploitDetail(tool.abc.SingleSpider):
    """
    WeGame云顶之弈比赛记录爬虫：游戏场次详情
    """

    _HEADERS = {"Accept-Encoding": "gzip",
                "Host": "mlol.qt.qq.com",
                "Connection": "Keep-Alive",
                "user-agent": "okhttp/3.12.0"}

    def running(self, skey, exploit_id, end_time, user_id):
        # 请求召唤师比赛记录
        response = tool.do_request(
            url="https://mlol.qt.qq.com/gorpc/exploit/exploit/query_exploit_detail/proxy",
            params={
                "exploit_id": exploit_id,
                "game_area": "1",
                "scene": "tft_mlol",
                "user_id": user_id,
                "endtime": end_time,
                "plat": "android",
                "version": "9914"
            },
            headers=self._HEADERS,
            cookies={"l_uin": "o12345678",  # o+QQ号
                     "p_uin": "o12345678",  # o+QQ号
                     "uin": "o12345678",  # o+QQ号
                     "skey": skey},  # 登录状态SKEY(需要通过模拟器+Fildder获得，有效期24小时左右)
            verify=False)

        exploit = response.json()

        if "info" not in exploit:
            print("Missing: info")
            return False
        if "exploit_detail" not in exploit["info"]:
            print("Missing: info - exploit_detail")
            return False
        if exploit["info"]["exploit_detail"] is None:
            print("Missing: info - exploit_detail - is None")
            return False
        if "exploit_id" not in exploit["info"]["exploit_detail"]:
            print("Missing: info - exploit_detail - exploit_id")
            return False
        if "end_time" not in exploit["info"]["exploit_detail"]:
            print("Missing: info - exploit_detail - end_time")
            return False
        if "game_match_type" not in exploit["info"]["exploit_detail"]:
            print("Missing: info - exploit_detail - game_match_type")
            return False
        if "duration" not in exploit["info"]["exploit_detail"]:
            print("Missing: info - exploit_detail - duration")
            return False
        if "specific_user_exploit" not in exploit["info"]["exploit_detail"]:
            print("Missing: info - exploit_detail - specific_user_exploit")
            return False
        if "buff_version" not in exploit["info"]["exploit_detail"]["specific_user_exploit"]:
            print("Missing: info - exploit_detail - specific_user_exploit - buff_version")
            return False
        if "member_exploit_list" not in exploit["info"]["exploit_detail"]:
            print("Missing: info - exploit_detail - member_exploit_list")
            return False

        member_list = [{} for _ in range(8)]
        member_info_list = [[] for _ in range(8)]

        for member_exploit in exploit["info"]["exploit_detail"]["member_exploit_list"]:
            if "user_id" not in member_exploit:
                print("Missing: info - exploit_detail - member_exploit_list - - user_id")
                return False
            if "nickname" not in member_exploit:
                print("Missing: info - exploit_detail - member_exploit_list - - nickname")
                return False
            if "ranking" not in member_exploit:
                print("Missing: info - exploit_detail - member_exploit_list - - ranking")
                return False
            if "piece_list" not in member_exploit:
                print("Missing: info - exploit_detail - member_exploit_list - - piece_list")
                return False
            if "game_rank_list" not in member_exploit:
                print("Missing: info - exploit_detail - member_exploit_list - - game_rank_list")
                return False
            if "full_rank_title" not in member_exploit["game_rank_list"][0]:
                print("Missing: info - exploit_detail - member_exploit_list - - game_rank_list - full_rank_title")
                return False

            ranking = int(member_exploit["ranking"])
            if ranking < 1 or ranking > 8:
                return False

            member_list[ranking - 1] = {
                "user_id": member_exploit["user_id"],
                "nickname": member_exploit["nickname"],
                "rank_title": member_exploit["game_rank_list"][0]["full_rank_title"]
            }

            if member_exploit["piece_list"] is None:
                print("Missing: info - exploit_detail - member_exploit_list - - piece_list - is None")
                continue

            for piece in member_exploit["piece_list"]:
                if "star_num" not in piece:
                    print("Missing: info - exploit_detail - member_exploit_list - - piece_list - - star_num")
                    return False
                if "hero_name" not in piece:
                    print("Missing: info - exploit_detail - member_exploit_list - - piece_list - - hero_name")
                    return False
                member_info_list[ranking - 1].append([
                    piece["hero_name"],
                    piece["star_num"]
                ])

        exploit_write = list()
        exploit_write.append({
            "exploit_id": exploit["info"]["exploit_detail"]["exploit_id"],
            "end_time": exploit["info"]["exploit_detail"]["end_time"],
            "game_match_type": exploit["info"]["exploit_detail"]["game_match_type"],
            "duration": exploit["info"]["exploit_detail"]["duration"],
            "version": exploit["info"]["exploit_detail"]["specific_user_exploit"]["buff_version"],
            "member_list": json.dumps(member_list, ensure_ascii=False),
            "member_1": json.dumps(member_info_list[0], ensure_ascii=False),
            "member_2": json.dumps(member_info_list[1], ensure_ascii=False),
            "member_3": json.dumps(member_info_list[2], ensure_ascii=False),
            "member_4": json.dumps(member_info_list[3], ensure_ascii=False),
            "member_5": json.dumps(member_info_list[4], ensure_ascii=False),
            "member_6": json.dumps(member_info_list[5], ensure_ascii=False),
            "member_7": json.dumps(member_info_list[6], ensure_ascii=False),
            "member_8": json.dumps(member_info_list[7], ensure_ascii=False)
        })

        return exploit_write


# ------------------- 单元测试 -------------------
if __name__ == "__main__":
    # 设置不需要代理的环境变量(解决request.exceptions.ProxyError:HTTPSConnectionPool的问题)
    os.environ["NO_PROXY"] = "mlol.qt.qq.com"

    print(SpiderTftExploitDetail().running(
        skey="MK3lj8yMoH",
        exploit_id="4508602428",
        end_time="1574935798",
        user_id="42b0a5ed-c1d9-4246-ac1b-67b02069b32c"))
